<template>
  <div ref="adContainer">
    <ins
      ref="adElement"
      class="adsbygoogle"
      :style="`display:block;width:100%;`"
      :data-ad-channel="channel"
      :data-ad-client="adsClientId"
      :data-ad-slot="adsenseId"
      data-full-width-responsive="true"
    ></ins>
  </div>
</template>

<script setup>
const props = defineProps({
    slotType: {
        type: String,
        required: true
    }
})

const hostname = useHostname()
const { getParam } = useUrlParams()
const channel = getParam('channel')

const adsClientId = getadsClientId(hostname)
const adsenseId = getAdsAdSlot(props.slotType, hostname)

// 监听广告加载完成
const adContainer = ref(null)
const adElement = ref(null)
const adObserver = ref(null)
// 观察广告是否返回广告
const handleAdObserver = () => {
  try {
    (window.adsbygoogle = window.adsbygoogle || []).push({})
  } catch (error) {
    logEvent('AFC_AD_Error', {
      AdSlot: adsenseId,
      Error: error.message
    })
    return
  }
  adObserver.value = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
          if (mutation.attributeName === 'data-ad-status') {
              const status = adElement.value.getAttribute('data-ad-status')
              if (status === 'filled') {
                  logEvent('AD_Show', {
                      AdSlot: adsenseId
                  });
              } else {
                  logEvent('AD_Show_Fail', {
                      AdSlot: adsenseId
                  });
                  // Remove unfilled ad container
                  // adElement.value.remove()
              }
              adObserver.value.disconnect()
          }
      })
  })
  adObserver.value.observe(adElement.value, {
      attributes: true,
      attributeFilter: ['data-ad-status']
  })
}

onMounted(() => {
  handleAdObserver()
})
onUnmounted(() => {
  adObserver.value.disconnect()
})
</script>

<style scoped>
  
</style>